<template>
  <i
    class="iconbox"
    :style="getIconStyle"
    ref="iconEl">
    <SvgIcon v-if="isSvg" :name="getSvgName"></SvgIcon>
  </i>
</template>

<script lang="ts" setup>
import { onMounted, ref, unref, watch, computed } from 'vue'
import Iconify from '@purge-icons/generated'
import { isNumber, isNaN } from 'lodash-es'
import SvgIcon from './SvgIcon.vue'

// eslint-disable-next-line no-undef
defineOptions({
  name: 'Icon'
})

const props = defineProps({
  name: String,
  color: String,
  size: [String, Number]
})

const iconEl = ref(null)

// 判断是否是本地 svg icon
const isSvg = computed(() => props.name?.startsWith('svg:'))
// 获取 svg name
const getSvgName = computed(() => props.name.replace('svg:', ''))

// 获取 icon 样式
const getIconStyle = computed(() => {
  const { color, size } = props

  let fontSize = '1em'

  if (isNumber(size) || !isNaN(size * 1)) {
    fontSize = size + 'px'
  } else if (size) {
    fontSize = size
  }
  return { fontSize, color }
})

// 生成icon
function createIcon (name:string) {
  const el = unref(iconEl)
  if (!el || !name || unref(isSvg)) return

  const svg = Iconify.renderSVG(name, {})

  if (svg) {
    el.textContent = ''
    el.appendChild(svg)
  } else {
    const span = document.createElement('span')
    span.className = 'iconify'
    span.dataset.icon = name
    el.textContent = ''
    el.appendChild(span)
  }
}

onMounted(() => {
  createIcon(props.name)
})

watch(() => props.name, name => {
  createIcon(name)
})
</script>

<style lang="less" scoped>
.iconbox {
  display: inline-block;
  vertical-align: middle;
  line-height: 0;
  svg {
    float: left;
  }
}
</style>
